package com.salton123.imagepicker.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.TextView;

import com.salton123.imagepciker.R;
import com.salton123.imagepicker.ImagePicker;
import com.salton123.imagepicker.bean.ImageItem;
import com.salton123.imagepicker.custom.ImagePickerTextRepository;
import com.salton123.imagepicker.log.ILog;
import com.salton123.imagepicker.util.BitmapUtil;
import com.salton123.imagepicker.util.Utils;
import com.salton123.imagepicker.view.CropImageView;

import java.io.File;
import java.util.ArrayList;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class ImageCropActivity extends ImageBaseActivity implements View.OnClickListener,
        CropImageView.OnBitmapSaveCompleteListener {

    private static final String TAG = "ImageCropActivity";

    private CropImageView mCropImageView;
    private Bitmap mBitmap;
    private boolean mIsSaveRectangle;
    private int mOutputX;
    private int mOutputY;
    private ArrayList<ImageItem> mImageItems;
    private ImagePicker imagePicker;
    private String imagePath;
    private TextView tvGuide;
    private TextView tvCancel;
    private TextView tvChoose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_crop);

        imagePicker = ImagePicker.getInstance();

        //初始化View
        tvCancel = findViewById(R.id.crop_cancel);
        tvCancel.setOnClickListener(this);
        if (!ImagePickerTextRepository.INSTANCE.getCancel().isEmpty()) {
            tvCancel.setText(ImagePickerTextRepository.INSTANCE.getCancel());
        }
        if (!imagePicker.getCropCancelText().isEmpty()) {
            tvCancel.setText(imagePicker.getCropCancelText());
        }
        if (!imagePicker.getCropCancelTextColor().isEmpty()) {
            tvCancel.setTextColor(Color.parseColor(imagePicker.getCropCancelTextColor()));
        }
        tvChoose = findViewById(R.id.crop_confirm);
        tvChoose.setOnClickListener(this);
        if (!ImagePickerTextRepository.INSTANCE.getChoose().isEmpty()) {
            tvChoose.setText(ImagePickerTextRepository.INSTANCE.getChoose());
        }
        if (!imagePicker.getCropChooselText().isEmpty()) {
            tvChoose.setText(imagePicker.getCropChooselText());
        }
        if (!imagePicker.getCropChooseTextColor().isEmpty()) {
            tvChoose.setTextColor(Color.parseColor(imagePicker.getCropChooseTextColor()));
        }
        tvGuide = findViewById(R.id.tv_crop_guide);
        if (!imagePicker.getCropTextGuide().isEmpty()) {
            tvGuide.setText(imagePicker.getCropTextGuide());
            tvGuide.setVisibility(View.VISIBLE);
        }
        if (!imagePicker.getCropTextColorGuide().isEmpty()) {
            tvGuide.setTextColor(Color.parseColor(imagePicker.getCropTextColorGuide()));
        }


        mCropImageView = findViewById(R.id.cv_crop_image);
        mCropImageView.setOnBitmapSaveCompleteListener(this);

        //获取需要的参数
        mIsSaveRectangle = imagePicker.isSaveRectangle();
        mImageItems = imagePicker.getSelectedImages();
        if (mImageItems.size() > 0) {
            imagePath = mImageItems.get(mImageItems.size() - 1).path; //取最后一张
        } else {
            ILog.e(TAG, "onCreate: mImageItems size <= 0");
            finish();
            return;
        }

        mCropImageView.setFocusStyle(imagePicker.getStyle());
        mCropImageView.setFocusWidth(imagePicker.getFocusWidth());
        mCropImageView.setFocusHeight(imagePicker.getFocusHeight());

        //缩放图片
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        options.inSampleSize = calculateInSampleSize(options, displayMetrics.widthPixels, displayMetrics.heightPixels);
        options.inJustDecodeBounds = false;
        mBitmap = BitmapFactory.decodeFile(imagePath, options);
//        mCropImageView.setImageBitmap(mBitmap);
        //设置默认旋转角度
        mCropImageView.setImageBitmap(mCropImageView.rotate(mBitmap, BitmapUtil.getBitmapDegree(imagePath)));
        mCropImageView.setRotateSwitch(imagePicker.isRotateSwitch());

//        mCropImageView.setImageURI(Uri.fromFile(new File(imagePath)));
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = width / reqWidth;
            } else {
                inSampleSize = height / reqHeight;
            }
        }
        return inSampleSize;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.crop_cancel) {
            setResult(RESULT_CANCELED);
            onBackPressed();
        } else if (id == R.id.crop_confirm) {
            float scaleX = mCropImageView.getImageMatrixRect().width() / imagePicker.getFocusWidth();
//            float scaleY = mCropImageView.getImageMatrixRect().height() / imagePicker.getFocusHeight();
            //因为裁剪框是正方形的,所以生成的图片应该也是正方形的
            if (imagePicker.getOutPutX() == 0) {
                mOutputX = (int) (BitmapUtil.getBitmapOption(imagePath).outWidth / scaleX);
            } else {
                mOutputX = imagePicker.getOutPutX();
            }
            if (imagePicker.getOutPutX() == 0) {
                mOutputY = mOutputX;
            } else {
                mOutputY = imagePicker.getOutPutY();
            }
            mCropImageView.saveBitmapToFile(imagePicker.getCropCacheFolder(this), mOutputX, mOutputY, mIsSaveRectangle);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        try {
            if (mImageItems.size() > 0) {
                mImageItems.remove(mImageItems.size() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBitmapSaveSuccess(File file) {
        //裁剪后替换掉裁剪前的原图，但是不要改变全局中的选中数据
        if (mImageItems.size() > 0) {
            mImageItems.remove(mImageItems.size() - 1);
        }
        ImageItem imageItem = new ImageItem();
        imageItem.path = file.getAbsolutePath();
        imageItem.size = file.length() / 1024;
        imageItem.width = mOutputX;
        imageItem.height = mOutputY;
        imageItem.name = file.getName();
        imageItem.mimeType = Utils.getMimeType(file.getAbsolutePath());
        mImageItems.add(imageItem); //把裁剪后的图片加进去

        if (mOutputX < imagePicker.getCropPixelLimit() || mOutputY < imagePicker.getCropPixelLimit()) {
            ILog.w(TAG, "onBitmapSaveSuccess: CropPixelLimit");
            if (imagePicker.getCropPixelLimitCallback() != null) {
                imagePicker.getCropPixelLimitCallback().onLimitToast(imageItem);
                onBackPressed();
                return;
            }
        }

        Intent intent = new Intent();
        intent.putExtra(ImagePicker.EXTRA_RESULT_ITEMS, mImageItems);
        setResult(ImagePicker.RESULT_CODE_ITEMS, intent);   //单选不需要裁剪，返回数据
        finish();
    }


    @Override
    public void onBitmapSaveError(File file) {
        ILog.d(TAG, "onBitmapSaveError: ");
        //裁剪失败就返回原图
        Intent intent = new Intent();
        intent.putExtra(ImagePicker.EXTRA_RESULT_ITEMS, mImageItems);
        setResult(ImagePicker.RESULT_CODE_ITEMS, intent);   //单选不需要裁剪，返回数据
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCropImageView.setOnBitmapSaveCompleteListener(null);
        if (null != mBitmap && !mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }
}
